﻿using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using WebApiExtend;
using WebApiExtend;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using WebApiExtend.Middleware;
using Microsoft.OpenApi.Models;

namespace WebApiExtend
{
    /// <summary>
    /// 入口点
    /// </summary>
    public static class Init
    {
        private static string corsName = "_myAllowSpecificOrigins";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        public static void ExUseBuilder(this WebApplicationBuilder builder)
        {
            //设置获取客户端IP信息
            builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            builder.Services.AddHttpClient(); 

            //配置时间格式
            builder.Services.AddControllersWithViews().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss fff"; //格式化时间
            });

            builder.Services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;//解决Swagger文档中样例参数说明中参数首字母变小写的问题 
            });

            //配置 JSON.NET
            builder.Services.AddControllers().AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;//忽略循环引用    
                opt.SerializerSettings.ContractResolver = new DefaultContractResolver();//不改变字段大小
            }); 

            //项目启动 先缓存所有实体反射对象
            //配置全局过滤器
            builder.Services.AddControllersWithViews(option =>
            {
                option.Filters.Add<ExecptionFilter>();
                option.Filters.Add<ResourceFilter>();
                option.Filters.Add<ActionFilter>();
                option.Filters.Add<ResultFilter>();
            });

            //配置可以跨域
            builder.Services.AddCors(options =>
            {
                options.AddPolicy(corsName, builder => builder.AllowAnyOrigin().AllowAnyHeader().WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS"));
            });


            //配置swagger
            builder.Services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Api标题",
                    Description = "api说明:<br />1.添加,修改 这些字段都不要传值: <b>isdel，addtime，lasttime，adduserid，lastuserid</b>"
                });

                options.OperationFilter<SwaggerHeaderFilter>();

                //加载全部文档xml
                DirectoryInfo root = new DirectoryInfo(AppContext.BaseDirectory);
                var files = root.GetFiles().Where(ex => Path.GetExtension(ex.Name).ToLower() == ".xml").Select(ex => ex.FullName).ToList();
                foreach (var file in files)
                {
                    options.IncludeXmlComments(file, true);
                }
            });
        }

        /// <summary>
        /// 注册所有中间件
        /// </summary>
        /// <param name="app">要进行扩展的类型</param>
        public static void ExUseApp(this IApplicationBuilder app)
        {
            //app.UseMiddleware<InitMiddleware>();//初始化入口中间件,处理最开始的默认值
            app.UseMiddleware<HeaderMiddleware>();//请求头
            app.UseMiddleware<LogMiddleware>();//日志
            //app.ExUseMappingFolder();//日志映射,兼容所有平台

            app.UseCors(corsName);//配置跨域
        } 
    }
}
